package com.ymt.bpm.util;


import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.logging.Logger;

import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * 模块处理工具，这里的模块指代流程可用组件.
 * @author Johnny
 *
 */
public class ModuleUtil {
	
	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(ModuleUtil.class.getName());
	
	/**
	 * get module names in ["module1", "module2"].
	 * @param realPath
	 * @return
	 */
	public static String getModuleNames(String realPath, String mParentPath) {
		logger.finer("getModuleNames path="+realPath + mParentPath);
		File mParentFolder = new File(realPath + mParentPath);
		if (mParentFolder.exists() && mParentFolder.isDirectory()) {
			File[] mList = mParentFolder.listFiles(new FileFilter(){
				@Override
				public boolean accept(File mFolder) {
					if (mFolder.isDirectory()) {
						logger.finer("getModuleNames module files="+Arrays.toString(mFolder.list()));
						String[] filenames = mFolder.list(new FilenameFilter(){
							@Override
							public boolean accept(File mFolderDir, String filename) {
								return filename.equalsIgnoreCase("prop.js");
							}
						});
						if(null == filenames){
							return false;
						}else{
							return filenames.length==1;
						}
					}
					return false;
				}}
			);
			if (mList != null && mList.length>0) {
				Arrays.sort(mList, new Comparator<File>(){
					@Override
					public int compare(File arg0, File arg1) {
						return arg0.getName().compareToIgnoreCase(arg1.getName());
					}
				});
				String[] rs = new String[mList.length];
				for (int i=0; i<mList.length; i++) {
					logger.finer("getModuleNames module folder="+mList[i].getName());
					rs[i] = "\"" + mList[i].getName() + "\"";
				}
				return Arrays.toString(rs);
			}
		} else {
			logger.warning("module path is not folder: "+mParentFolder);
		}
		return null;
	}
	
	/**
	 * import modules.
	 * @param engine
	 * @param file
	 * @throws IOException
	 * @throws ScriptException
	 */
	public static void importFile(ScriptEngine engine, File file) throws IOException, ScriptException {
		InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");

		engine.eval(isr);
	}
	
}
